package com.shujia.scala

import scala.io.Source

object Demo25Student {
  def main(args: Array[String]): Unit = {
    /**
      * 1、统计班级人数
      * 2、统计学生的总分
      *
      */


    /**
      * 1、统计班级人数
      */
    //1、读取学生表数据
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList

    //取出每个学生的班级
    val clazzs: List[String] = students.map(student => {
      val split: Array[String] = student.split(",")
      //取出班级
      split(4)
    })

    //按照班级分组
    val groupBy: Map[String, List[String]] = clazzs.groupBy(clazz => clazz)

    //计算班级的人数
    val clazzCount: Map[String, Int] = groupBy.map((kv: (String, List[String])) => {
      //班级
      val clazz: String = kv._1
      //一个班级对于所有的value
      val values: List[String] = kv._2

      val count: Int = values.length

      (clazz, count)
    })

    clazzCount.foreach(println)

    println("=" * 100)

    /**
      *
      * 2、统计学生的总分
      */

    //读取分数表
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList

    //取出学号和分数
    val kvScore: List[(String, Int)] = scores.map(score => {
      val split: Array[String] = score.split(",")
      //学号
      val id: String = split(0)
      //分数
      val sco: Int = split(2).toInt
      (id, sco)
    })

    //按照学号分组
    val groupByScore: Map[String, List[(String, Int)]] = kvScore.groupBy(kv => kv._1)


    //计算总分
    val sumScore: Map[String, Int] = groupByScore.map((kv: (String, List[(String, Int)])) => {
      val id: String = kv._1
      val scos: List[(String, Int)] = kv._2
      //取出每科的分数
      val ints: List[Int] = scos.map(i => i._2)
      //分数求和
      val sumScore: Int = ints.sum
      (id, sumScore)
    })


    sumScore.foreach(println)
  }
}
